<template>
	<view class="container">
		<view class="revise-back">
			<image class="revise-back-img" :src="userData.backdrop" mode="aspectFill"></image>
			<view class="backdrop-overlay"></view>
			<view class="revise-avater global-display global-f-direction global-a-items">
				<view class="avatar-container">
					<image :src="userData.avatarUrl" class="personal-margin" mode="aspectFill" @click="uploadAvatarurl(0)"></image>
					<view class="avatar-edit-hint">点击修改</view>
				</view>
				<view class="backdrop-btn" @click="uploadAvatarurl(1)">设置背景</view>
			</view>
		</view>
		<view class="personal-view">
			<view class="form-item global-display global-a-items">
				<text class="label">昵称</text>
				<input class="input-field" type="text" placeholder="请填写昵称" v-model="userData.nickname">
			</view>
			<view class="form-item global-display global-a-items">
				<text class="label">性别</text>
				<picker @change="pickerChangeGender" :range="['男','女']">
					<view class="picker-field global-display global-a-items">
						<input class="input-field" type="text" disabled placeholder="请选择性别" v-model="userData.gender">
						<image src="/static/icon/personal-Data/jiantou-you.png" mode="widthFix"></image>
					</view>
				</picker>
			</view>
			<view class="form-item global-display global-a-items">
				<text class="label">出生日期</text>
				<picker @change="pickerChangeDate" mode="date" :start="startDate" :end="endDate">
					<view class="picker-field global-display global-a-items">
						<input class="input-field" type="text" disabled placeholder="请选择出生日期" v-model="userData.birthday">
						<image src="/static/icon/personal-Data/jiantou-you.png" mode="widthFix"></image>
					</view>
				</picker>
			</view>
			<view class="form-item global-display global-a-items">
				<text class="label">常居城市</text>
				<picker @change="pickerChangeCity" mode="region" level="city">
					<view class="picker-field global-display global-a-items">
						<input class="input-field" type="text" disabled placeholder="请选择常居城市" v-model="userData.city">
						<image src="/static/icon/personal-Data/jiantou-you.png" mode="widthFix"></image>
					</view>
				</picker>
			</view>
		</view>
		<button @click="subMit" class="sum-mit">保存修改</button>
	</view>
</template>

<script setup lang="ts">
	import {reactive, ref,onMounted} from 'vue'
	import moment from 'moment'
	moment.locale('zh-cn');
	import {upLoadCos} from '@/utils/cos'
	import {editPersonalAPI} from '@/api/personal'
	
	// 获取本地缓存的用户资料
	onMounted(()=>{
		const userInfor = uni.getStorageSync('userInfor')
		const {avatarUrl,backdrop,nickname,gender,birthday,city} = userInfor
		userData.avatarUrl = avatarUrl
		userData.backdrop = backdrop
		userData.nickname = nickname
		userData.gender = gender
		userData.birthday = birthday
		userData.city = city
	})
	
	// 存储用户资料数据
	const userData = reactive({
		backdrop:'',
		avatarUrl:'',
		nickname:'',
		gender:'',
		birthday:'',
		city:''
	})
	
	// 表单验证状态
	const formValid = ref(true)
	const errorMsg = ref('')
	
	// 显示错误提示
	function showError(msg: string) {
		formValid.value = false
		errorMsg.value = msg
		wx.showToast({
			title: msg,
			icon: 'none',
			duration: 2000
		})
	}
	
	// 验证表单
	function validateForm() {
		formValid.value = true
		
		if (!userData.avatarUrl) {
			showError('请上传头像')
			return false
		}
		
		if (!userData.backdrop) {
			showError('请设置背景图')
			return false
		}
		
		if (!userData.nickname || userData.nickname.trim().length < 2) {
			showError('昵称不能少于2个字符')
			return false
		}
		
		if (!userData.gender) {
			showError('请选择性别')
			return false
		}
		
		if (!userData.birthday) {
			showError('请选择出生日期')
			return false
		}
		
		if (!userData.city) {
			showError('请选择常居城市')
			return false
		}
		
		return true
	}
	
	// 上传头像背景图
	async function uploadAvatarurl(event:number){
		wx.chooseMedia({
		  count: 1, // 限制为1张图片
		  mediaType: ['image'],
		  sizeType:['compressed'],
		  sourceType: ['album', 'camera'],
		  success:async(res)=> {
			wx.showLoading({title: '上传中',mask:true})
			try{
				const upLoadRes = await upLoadCos(res.tempFiles)
				if(event === 0){
					userData.avatarUrl = upLoadRes[0]
					wx.showToast({
						title: '头像上传成功',
						icon: 'success',
						duration: 1500
					})
				}else{
					userData.backdrop = upLoadRes[0]
					wx.showToast({
						title: '背景上传成功',
						icon: 'success',
						duration: 1500
					})
				}
			}catch(err){
				console.log(err);
				wx.showToast({title: '上传失败',icon: 'error',duration: 800})
			}
		  }
		})
	}
	
	// 选择性别
	function pickerChangeGender(event:any){
		userData.gender = event.detail.value === "0" ? '男' : '女'
	}
	
	// 选择生日
	const year = moment().format('YYYY-MM-DD')//当前年
	const startDate = ref('1930-01-01')
	const endDate = ref(year)
	function pickerChangeDate(event:any){
		userData.birthday = event.detail.value
	}
	
	// 选择省市区
	function pickerChangeCity(event:any){
		let str = ''
		event.detail.value.forEach((item:string)=>str += item)
		userData.city = str
	}
	
	// 提交中状态
	const isSubmitting = ref(false)
	
	// 提交
	async function subMit(){
		if (isSubmitting.value) return
		
		// 验证表单
		if (!validateForm()) return
		
		isSubmitting.value = true
		wx.showLoading({title: '更新中',mask:true})
		
		try {
			const res = await editPersonalAPI(userData)
			
			if (res && res.data) {
				const {age,avatarUrl,backdrop,birthday,city,gender,nickname} = res.data.res
				console.log('res.data',res.data);
				const userJson = uni.getStorageSync('userInfor')
				console.log('userJson',userJson);
				
				userJson.age = age
				userJson.avatarUrl = avatarUrl
				userJson.backdrop = backdrop
				userJson.birthday = birthday
				userJson.city = city
				userJson.gender = gender
				userJson.nickname = nickname
				wx.setStorageSync('userInfor',userJson)
				uni.$emit('uploadUserdata',true)
				
				wx.showToast({
					title: '资料更新成功',
					icon: 'success',
					duration: 1500
				})
				
				setTimeout(() => {
					wx.navigateBack({delta: 1})
				}, 1500)
			} else {
				wx.showToast({
					title: '更新失败，请重试',
					icon: 'none',
					duration: 2000
				})
			}
		} catch (error) {
			console.error('更新资料失败:', error)
			wx.showToast({
				title: '更新失败，请重试',
				icon: 'none',
				duration: 2000
			})
		} finally {
			isSubmitting.value = false
		}
	}
</script>

<style scoped>
.container {
	min-height: 100vh;
	background-color: #f8f8f8;
	padding-bottom: 60rpx;
}
.revise-back{
	height: 500rpx;
	overflow: hidden;
	position: relative;
	box-shadow: 0 10rpx 20rpx rgba(0, 0, 0, 0.1);
}
.revise-back-img{
	height: 500rpx;
	width: 100%;
	transition: transform 0.3s ease;
} 
.revise-back:hover .revise-back-img {
	transform: scale(1.05);
}
.backdrop-overlay {
	position: absolute;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background: linear-gradient(to bottom, rgba(0,0,0,0.1), rgba(0,0,0,0.4));
}
.revise-avater{
	position: absolute;
	left:50%;
	top:50%;
	transform:translate(-50%,-50%);
	z-index: 2;
}
.avatar-container {
	position: relative;
	margin-bottom: 20rpx;
}
.personal-margin{
	width: 180rpx;
	height: 180rpx;
	border-radius: 50%;
	border: 8rpx solid rgba(255, 255, 255, 0.8);
	box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.15);
	transition: transform 0.3s ease, filter 0.3s ease;
}
.personal-margin:active {
	transform: scale(0.95);
}
.avatar-edit-hint {
	position: absolute;
	bottom: 0;
	left: 0;
	right: 0;
	background-color: rgba(0, 0, 0, 0.5);
	color: white;
	font-size: 24rpx;
	padding: 6rpx 0;
	text-align: center;
	border-bottom-left-radius: 90rpx;
	border-bottom-right-radius: 90rpx;
	opacity: 0;
	transition: opacity 0.3s ease;
}
.avatar-container:hover .avatar-edit-hint {
	opacity: 1;
}
.avatar-container:hover .personal-margin {
	filter: brightness(0.9);
}
.backdrop-btn{
	background-color: rgba(255, 255, 255, 0.9);
	margin-top: 20rpx;
	padding: 12rpx 36rpx;
	display: block;
	border-radius: 30rpx;
	font-size: 28rpx;
	font-weight: 500;
	box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
	transition: all 0.3s ease;
}
.backdrop-btn:active {
	transform: scale(0.95);
	box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.1);
}
.personal-view{
	background-color: #ffffff;
	border-radius: 24rpx;
	margin: -60rpx 30rpx 40rpx;
	padding: 30rpx 0 10rpx;
	box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.05);
	position: relative;
	z-index: 3;
}
.form-item {
	border-bottom: 2rpx solid #f2f2f2;
	padding: 30rpx 30rpx;
	transition: background-color 0.2s ease;
}
.form-item:last-child {
	border-bottom: none;
}
.form-item:active {
	background-color: #f9f9f9;
}
.label {
	width: 150rpx;
	font-size: 32rpx;
	color: #333;
	font-weight: 500;
}
.input-field {
	flex: 1;
	font-size: 30rpx;
	color: #666;
	height: 60rpx;
	line-height: 60rpx;
}
.input-field::placeholder {
	color: #bbb;
}
.picker-field {
	flex: 1;
}
.picker-field image {
	width: 30rpx;
	opacity: 0.6;
	margin-left: 20rpx;
}
.sum-mit{
	background: linear-gradient(135deg, #ffeb3b 0%, #f9dc53 100%);
	width: 80%;
	margin-top: 60rpx;
	border: none;
	border-radius: 50rpx;
	font-size: 32rpx;
	font-weight: 600;
	padding: 24rpx 0;
	color: #333;
	letter-spacing: 4rpx;
	box-shadow: 0 8rpx 20rpx rgba(249, 220, 83, 0.3);
	transition: all 0.3s ease;
}
.sum-mit:active {
	transform: translateY(4rpx);
	box-shadow: 0 4rpx 10rpx rgba(249, 220, 83, 0.2);
}
</style>